# 创建时间:2023/1/30 23:24
# 创建人:天霄
# 计划 :SenjoTwintail
# 文件 :GameStart.py
# 基于 Python 3.8.2
# ========================================
# 游戏开始（pygame运行）
# ========================================
from vars import *
import first
import sys
import pygame

from BasePygame.Gamer import SpriteCommon, change_image, load
from BasePygame.Public import flagBox, font1, fontB, fontE, fontDefault
from PyGameUI.Use import soundBox
from PyGameUI.Use.AsyncGenerate import genAsync
from PyGameUI.Page import uiApi, savings, LoginPage, HomePage, DirectoryPage


def start():
    pygame.event.set_blocked(None)  # 禁止所有事件
    screen_sizeRect = first.screen_sizeRect
    screen_center = first.screen_center
    screen = first.screen
    pygame.display.set_caption(CONST.TITLE)
    pygame.mouse.set_visible(False)
    icon = change_image(uiApi.getUiPicture('icon')[0])
    pygame.display.set_icon(icon)

    # ====文字====
    # myfont = pygame.font.Font(uiApi.getPathFont('font1'), 20)
    myfont = font1
    to_player_text = '谨以此纪念永远的战场双马尾。'
    to_player_text2 = '——开发者：天霄九重'
    text_setup = myfont.render(to_player_text, (255, 0, 0), size=25)[0].convert_alpha()
    text_setup2 = fontDefault.render(to_player_text2, (255, 0, 0), size=15)[0].convert_alpha()
    set_text_tps = lambda tps: myfont.render(f'当前刷新率：{tps}', (255, 0, 0), size=20)[0].convert_alpha()
    text_setupRect = text_setup.get_rect()  # 获取显示对象的rect区域坐标
    text_setupRect.center = screen_center  # 居中
    text_setupRect2 = text_setup2.get_rect()  # 获取显示对象的rect区域坐标
    text_setupRect2.bottomright = first.screen_sizeRect.bottomright  # 右下角
    text_tps = set_text_tps(60)
    text_tpsRect = text_tps.get_rect()
    # print(f'{text_tpsRect=}')

    # ====图片====
    touch_pic = uiApi.getUiPicture('touchguide')[0]
    touch = SpriteCommon(touch_pic, (2, 114, 75, 96), 0, 0.4)
    touched = change_image(touch_pic, (2, 2, 107, 108), 0, 0.4)
    flagBox.touchRect = touch.rect
    flagBox.touchedRect = touched.get_rect()
    # print(flagbox.touchedRect)
    # 色块
    # face = pygame.Surface((50,50))
    # face.fill('pink')

    # ====声音====
    my_event = pygame.event.Event(flagBox.MUSICENDEVENT, message='music end!')
    pygame.event.post(my_event)
    pygame.mixer.music.set_endevent(flagBox.MUSICENDEVENT)

    # ====绘制====
    load.loading()
    clock = pygame.time.Clock()
    screen.fill('black')
    screen.blit(text_setup, text_setupRect)  # 绘制
    screen.blit(text_setup2, text_setupRect2)  # 绘制
    pygame.display.flip()
    pygame.time.wait(1000)
    genAsync.results['favor_scenebg_list'] = genAsync.generate_bgsGo()  # 0:00:01.604746

    pygame.event.set_allowed(None)
    pygame.event.set_blocked(flagBox.blockEvents)
    here = LoginPage(touch)
    while True:
        clock.tick(flagBox.fps)  # 通过时钟对象，指定循环频率，每秒循环60次
        flagBox.clickable = True
        flagBox.clicked = False
        flagBox.clickedRight = False
        flagBox.moving = False
        flagBox.fondled = False
        flagBox.fondled_where = None
        flagBox.rel = (0, 0)
        flagBox.pressed = pygame.mouse.get_pressed()
        flagBox.clickOnce = [False, False, False,  0, 0]
        flagBox.setWASD(-10)
        # ===============1、事件捕获/简单处理区===================
        for event in pygame.event.get():
            # event = pygame.event.wait()
            if event.type == pygame.QUIT:
                pygame.quit()
                return
            if event.type == pygame.MOUSEMOTION:
                flagBox.rel = event.rel
                # print(flagBox.rel)
                flagBox.moving = True
            if event.type == pygame.MOUSEBUTTONDOWN:
                print(f'鼠标按下瞬时位置：{event.pos}, {event.button}。鼠标位置：{flagBox.touchRect}，按钮：{flagBox.where_in}')
                if event.button == pygame.BUTTON_LEFT:
                    flagBox.clickOnce[0] = True
                if event.button == pygame.BUTTON_MIDDLE:
                    flagBox.clickOnce[1] = True
                if event.button == pygame.BUTTON_RIGHT:
                    flagBox.clickOnce[2] = True
                if event.button == pygame.BUTTON_WHEELUP:
                    flagBox.clickOnce[3] = event.button
                if event.button == pygame.BUTTON_WHEELDOWN:
                    flagBox.clickOnce[4] = event.button
                # musicBox.play('fn03')
                # flagbox.setTrue('music_playing')
            if event.type == pygame.MOUSEBUTTONUP:
                if event.button == pygame.BUTTON_LEFT:
                    flagBox.clicked = True  # 是否点击了鼠标并已抬起
                if event.button == pygame.BUTTON_RIGHT:
                    flagBox.clickedRight = True
                # print(f'鼠标弹起瞬时位置：{event.pos}')  # 这个可以直接用即时位置

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    flagBox.fps += 5
                    flagBox.tps_changed = True
                    flagBox.tps_changed_start = pygame.time.get_ticks()
                    flagBox.fps = min(max(1, flagBox.fps), 500)
                    savings.set_fps(flagBox.fps)
                if event.key == pygame.K_LEFT:
                    flagBox.fps -= 5
                    flagBox.tps_changed = True
                    flagBox.tps_changed_start = pygame.time.get_ticks()
                    flagBox.fps = min(max(1, flagBox.fps), 500)
                    savings.set_fps(flagBox.fps)
                if event.key == pygame.K_t:
                    flagBox.tps_changed = True
                    flagBox.tps_changed_start = pygame.time.get_ticks()
                if event.key == pygame.K_w:
                    flagBox.setWASD(0)
                if event.key == pygame.K_a:
                    flagBox.setWASD(1)
                if event.key == pygame.K_s:
                    flagBox.setWASD(2)
                if event.key == pygame.K_d:
                    flagBox.setWASD(3)
                print(f'键盘弹起，此时帧率：{flagBox.fps}，按钮：{event.unicode} {event.key} {event.scancode} {event.mod}，WASD：{flagBox.wasd}')
                if event.key == pygame.K_SPACE:
                    flagBox.music_playing = not flagBox.music_playing
                if event.key == pygame.K_p:
                    pygame.mixer.music.stop()
                    flagBox.music_playing = False
            if event.type == flagBox.MUSICENDEVENT:  # 音乐播放完毕事件
                flagBox.music_playing = False

        mouse_loc = pygame.mouse.get_pos()
        touch_loc = [mouse_loc[0] - 11, mouse_loc[1]]
        flagBox.touchRect[0], flagBox.touchRect[1] = touch_loc

        # =============2、事件处理区=============
        # if flagbox.music_playing and not pygame.mixer.music.get_busy():
        #     pygame.mixer.music.unpause()
        #     print('暂停取消')
        # elif not flagbox.music_playing and pygame.mixer.music.get_busy():
        #     pygame.mixer.music.pause()
        #     print('暂停')
        # =========4、音乐播放区==========
        # now = pygame.time.get_ticks()
        # print(f'{now}绘图前：{flagBox.where_in=}')
        here.drawAll()
        # print(f'{now}绘图后：{flagBox.where_in=}')
        pygame.mixer.music.set_volume(savings.voice_soldier/100)
        if flagBox.clicked:
            soundBox.play_click()
        if flagBox.playRightClick:
            soundBox.play_clickRight()
        if flagBox.page == 'login':  # 播放背景音乐
            soundBox.play_bgm()
            flagBox.page = 'login_ready'
            print(flagBox.page, '=' * 20)

        if flagBox.herePageClickTo == 'home':
            flagBox.herePageClickTo = None
            flagBox.clicked = False
            load.loading()
            screen.fill('black')
            del here
            here = HomePage(touch)
            soundBox.change_bgm('home')
            soundBox.play_bgm()
            flagBox.page = 'home_ready'
            print(flagBox.page, '=' * 20)
            continue
        elif flagBox.herePageClickTo == 'directory':
            flagBox.herePageClickTo = None
            flagBox.clicked = False
            load.loading()
            screen.fill('black')
            del here
            here = DirectoryPage(touch)
            soundBox.change_bgm('directory')
            soundBox.play_bgm()
            flagBox.page = 'directory_ready'
            print(flagBox.page, '=' * 20)
            continue

        # ==================3、绘图区、页面跳转判断==================
        if flagBox.tps_changed and pygame.time.get_ticks() - flagBox.tps_changed_start <= 1500:
            text_tps = set_text_tps(flagBox.fps)
            text_tpsRect = text_tps.get_rect()
            text_tpsRect.topright = screen_sizeRect.topright
            screen.blit(text_tps, text_tpsRect)
        if flagBox.pressed[0]:
            flagBox.touchedRect.center = mouse_loc
            screen.blit(touched, flagBox.touchedRect)
            # print(f'鼠标即时位置：{mouse_loc}')
        if flagBox.clicked:
            print(f'鼠标弹起，位置：{mouse_loc}')
        screen.blit(touch.image, flagBox.touchRect)  # 绘制
        pygame.display.update()

        # elif flagBox.page == 'home':pass


if __name__ == '__main__':
    start()
    savings.record_logoutTime()
    print('=-' * 20)
    sys.exit(0)
